package com.lvyq.myplayer.ui.fragment.setting

import android.app.ProgressDialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.lvyq.myplayer.R
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.Preference
import androidx.preference.SwitchPreferenceCompat
import com.lvyq.myplayer.common.shared.PlayingDownloadSharedPrefsManager
import com.lvyq.myplayer.common.util.UpVersion
import com.lvyq.myplayer.ui.activity.setting.AboutActivity
import com.lvyq.myplayer.ui.activity.setting.WebViewActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

/**
 * 文件描述：SettingFragment
 * 作者：lvyq
 * 创建时间：2025-02-11
 * 修改时间：2025-02-11
 */


class SettingFragment : PreferenceFragmentCompat(),UpVersion {



    /**
     * 每次进入界面时，计算当前的缓存大小，包括内部存储和外部存储
     */
    override fun onResume() {
        super.onResume()
        // 每次进入页面时更新缓存大小
        updateCacheSizeDisplay()
        //初始化版本
        updateVersion()
    }

    private fun updateVersion() {
        context?.let {
            var appVersionName = getAppVersionName(it)
            findPreference<Preference>("about")?.summary = appVersionName
        }
    }


    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        // 加载 XML 布局
        setPreferencesFromResource(R.xml.setting, rootKey)

        // ===== 事件绑定 =====
        // 清理缓存点击
        findPreference<Preference>("clear_cache")?.setOnPreferenceClickListener {
            // 实际应执行清理逻辑
            clearAppCache()
            true
        }

        // 获取“边听边存”开关
        val downloadWhilePlayingPreference = findPreference<SwitchPreferenceCompat>("download_while_playing")
        // 初始化开关状态
        var isPlayingDownloadEnabled =  PlayingDownloadSharedPrefsManager.getState(requireContext())
        downloadWhilePlayingPreference?.isChecked =isPlayingDownloadEnabled
        // 监听开关状态变化
        downloadWhilePlayingPreference?.setOnPreferenceChangeListener { preference, newValue ->
            isPlayingDownloadEnabled = newValue as Boolean
            if (isPlayingDownloadEnabled) {
                // 开启“边听边存”功能
                enableDownloadWhilePlaying()
            } else {
                // 关闭“边听边存”功能
                disableDownloadWhilePlaying()
            }
            true
        }


        // 关于页面
        findPreference<Preference>("about")?.setOnPreferenceClickListener {
            // 跳转到关于页面（示例）
            startActivity(Intent(requireContext(), AboutActivity::class.java))
            true
        }
        //隐私政策
        findPreference<Preference>("privacy")?.setOnPreferenceClickListener {
            // 跳转页面
            showLocalAgreement("privacy_policy")
            true
        }
        //服务条款
        findPreference<Preference>("service")?.setOnPreferenceClickListener {
            showLocalAgreement("terms_of_service")
            true
        }
        //免责声明
        findPreference<Preference>("disclaimer")?.setOnPreferenceClickListener {
            showLocalAgreement("disclaimer")
            true
        }
        //开源地址
        findPreference<Preference>("gitee_address")?.setOnPreferenceClickListener {
            var url ="https://gitee.com/BuYaoPenXiangShui/xiangshui-music-player";
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
            startActivity(intent)
            true
        }

    }

    private fun clearAppCache() {
        // 显示清理进度对话框
        val dialog = ProgressDialog.show(
            context,
            "清理缓存",
            "正在释放存储空间...",
            true,
            false
        )

        // 在后台线程执行清理操作
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                // 清理内部缓存
                deleteDir(context?.cacheDir)
                // 清理外部私有缓存（如果有）
                deleteDir(context?.externalCacheDir)

                // 更新 UI（需切换回主线程）
                withContext(Dispatchers.Main) {
                    dialog.dismiss()
                    Toast.makeText(context, "缓存已清理", Toast.LENGTH_SHORT).show()
                    updateCacheSizeDisplay()
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    dialog.dismiss()
                    Toast.makeText(context, "清理失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    // 递归删除目录及其内容
    private fun deleteDir(dir: File?): Boolean {
        return dir?.let { file ->
            if (file.isDirectory) {
                file.listFiles()?.forEach { deleteDir(it) }
            }
            file.delete()
        } ?: false
    }


    private fun updateCacheSizeDisplay() {
        lifecycleScope.launch(Dispatchers.IO) {
            val cacheSize = getCacheSize()
            val cacheSizeStr = formatSize(cacheSize)

            // 切换回主线程更新 UI
            withContext(Dispatchers.Main) {
                findPreference<Preference>("clear_cache")?.summary = cacheSizeStr
            }
        }
    }

    // 计算缓存大小（内部 + 外部）
    private fun getCacheSize(): Long {
        var totalSize: Long = 0

        // 内部缓存
        context?.cacheDir?.let {
            totalSize += getFolderSize(it)
        }

        // 外部缓存（需权限，Android 10+ 可能受限）
        context?.externalCacheDir?.let {
            totalSize += getFolderSize(it)
        }

        return totalSize
    }

    // 递归计算目录大小
    private fun getFolderSize(file: File): Long {
        var size: Long = 0
        if (file.isDirectory) {
            file.listFiles()?.forEach {
                size += getFolderSize(it)
            }
        } else if (file.exists()) {
            size += file.length()
        }
        return size
    }

    // 格式化大小（B -> KB/MB/GB）
    private fun formatSize(size: Long): String {
        return when {
            size < 1024 -> "$size B"
            size < 1024 * 1024 -> String.format("%.1f KB", size / 1024f)
            size < 1024 * 1024 * 1024 -> String.format("%.1f MB", size / (1024f * 1024f))
            else -> String.format("%.1f GB", size / (1024f * 1024f * 1024f))
        }
    }


    //本地化的协议内容展示
    private fun showLocalAgreement(type: String) {
        WebViewActivity.start(requireContext(),type)
    }


    private fun enableDownloadWhilePlaying() {
        PlayingDownloadSharedPrefsManager.putState(requireContext(),true)
        Toast.makeText(context, "边听边存已开启", Toast.LENGTH_SHORT).show()
    }

    private fun disableDownloadWhilePlaying() {
        PlayingDownloadSharedPrefsManager.putState(requireContext(),false)
        Toast.makeText(context, "边听边存已关闭", Toast.LENGTH_SHORT).show()
    }

}